package com.orange.controller;


import com.github.pagehelper.PageInfo;
import com.orange.commons.Constant;
import com.orange.commons.Result;
import com.orange.commons.UploadPathBean;
import com.orange.domain.User;
import com.orange.dto.UserDto;
import com.orange.service.UserService;
import com.orange.service.VisitLogService;
import com.orange.utils.MD5Util;
import com.orange.utils.WebMvcUtil;
import lombok.Cleanup;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Emp
 * @projectName: crm
 * @package: com.powernode.controller
 * @className: UserController
 * @description: TODO
 * @date: 2021/11/29 19:17
 * @version: 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UploadPathBean uploadPathBean;

    @Resource
    private VisitLogService visitLogService;

    /**
     * 分页查询所有用户
     * @param userDto
     * @return
     */
    @RequestMapping("list.do")
    public Result list(UserDto userDto) {
        PageInfo pageInfo = userService.queryUserByPage(userDto);
        return new Result(0, "查詢成功", pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 添加新用户,密码MD5加密保存
     * @param user
     * @return
     */
    @RequestMapping("addUser.do")
    public Result addUser(User user) {
        try {
            user.setPassword(MD5Util.md5(Constant.USER_DEFAULT_PWD));
            user.setCreateTime(new Date());
            String defaultImg = uploadPathBean.getUploadPath()+uploadPathBean.getDefaultImg();
            user.setImg(defaultImg);
            int i = userService.insertSelective(user);
            return i == 1 ? Result.USER_ADD_SUCCESS : Result.USER_ADD_ERROR;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.USER_ADD_ERROR;
        }
    }

    /**
     * 修改用户信息,@username,@realname,@role字段
     * @param user
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("updateUser.do")
    public Result updateUser(User user) {
        try {
            int i = userService.updateByPrimaryKeySelective(user);
            visitLogService.updateRealname(user);
            return i == 1 ? Result.USER_UPDATE_SUCCESS : Result.USER_UPDATE_ERROR;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.USER_UPDATE_ERROR;
        }
    }

    /**
     * 用户离职,修改@deleted字段
     * @param user
     * @return
     */
    @RequestMapping("quitUser.do")
    public Result quitUser(User user) {
        try {
            user.setDeleted(Constant.USER_DELETED_2);
            int i = userService.updateByPrimaryKeySelective(user);
            return i == 1 ? Result.USER_OPT_SUCCESS : Result.USER_OPT_ERROR;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.USER_OPT_ERROR;
        }
    }

    /**
     * 重置密码,修改@password字段
     * @param user
     * @return
     */
    @RequestMapping("resetPwd.do")
    public Result resetPwd(User user) {
        try {
            user.setPassword(MD5Util.md5(Constant.USER_DEFAULT_PWD));
            int i = userService.updateByPrimaryKeySelective(user);
            return i == 1 ? Result.USER_OPT_SUCCESS : Result.USER_OPT_ERROR;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.USER_OPT_ERROR;
        }
    }

    /**
     * 修改密码,修改@password字段,验证旧密码与新密码
     * @param oldPwd
     * @param newPwd
     * @param newPwd2
     * @return
     */
    @RequestMapping("updatePwd.do")
    public Result updatePwd(String oldPwd, String newPwd, String newPwd2) {
        if (!newPwd.equals(newPwd2)) {
            return Result.USER_UPDATE_ERROR;
        }
        try {
            User user = (User) WebMvcUtil.getSession().getAttribute(Constant.SESSION_USER_KEY);
            Integer id = user.getId();
            User u = userService.selectByPrimaryKey(id);
            if (null == oldPwd || "".equals(oldPwd)){
                return Result.USER_UPDATE_ERROR;
            }
            if (!MD5Util.md5(oldPwd).equals(u.getPassword())){
                return Result.USER_UPDATE_ERROR;
            }
            u.setPassword(MD5Util.md5(newPwd));
            int i = userService.updateByPrimaryKeySelective(u);
            return i == 1 ? Result.USER_UPDATE_SUCCESS : Result.USER_UPDATE_ERROR;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.USER_UPDATE_ERROR;
        }
    }

    /**
     * 查询所有在职业务员
     * @return
     */
    @RequestMapping("queryAllAvailableUser.do")
    public Result queryAllAvailableUser(){
        User user = WebMvcUtil.getCurrentUser();
        if (user.getRole().equals(Constant.USER_ROLE_1)){
            List<User> userList = userService.queryAvailableUser();
            return new Result(200,"查询成功",0L,userList);
        }
        return Result.USER_OPT_ERROR;
    }

    /**
     * 修改头像,修改@img字段,按时间分配文件夹并保存文件路径
     * @param name
     * @param file
     * @return
     */
    @RequestMapping("updateHeadPortrait.do")
    public Result updateHeadPortrait(String name, MultipartFile file){
        try {
            String uploadPath = uploadPathBean.getUploadPath();
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd/HH/mm/ss/");
            String formatDate = format.format(new Date());
            String prefixPath=uploadPath+formatDate;
            String orgName = file.getOriginalFilename();

            String path=prefixPath+createFileName(orgName);
            User user = WebMvcUtil.getCurrentUser();
            user.setImg(path);
            File fileUpload = new File(path);
            if (!fileUpload.exists()){
                boolean mkdirs = fileUpload.mkdirs();
            }
            file.transferTo(fileUpload);
            this.userService.updateByPrimaryKeySelective(user);
            return Result.USER_OPT_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.USER_OPT_ERROR;
        }
    }

    /**
     * 生成头像文件名
     * @param org
     * @return
     */
    public static String createFileName(String org){
        String suffix = org.substring(org.lastIndexOf("."));
        return UUID.randomUUID().toString().replace("-","").toUpperCase()+suffix;
    }

    /**
     * 显示头像,从用户@img字段中的路径读取头像,并写出到网页
     * @param response
     * @throws Exception
     */
    @RequestMapping("imgDownload.do")
    public void imgDownload(HttpServletResponse response) throws Exception {
        String img = WebMvcUtil.getCurrentUser().getImg();
        File file = new File(img);
        @Cleanup BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        @Cleanup BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        byte[] car = new byte[1024];
        int len=0;
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        String imgName = img.substring(img.lastIndexOf("/")+1);
        response.setHeader("Content-Disposition","attachment;filename=\""+imgName+"\"");
        while ((len=bis.read(car))!=-1){
            bos.write(car,0,len);
        }
    }

    /**
     * 验证旧密码
     * @param oldPwd
     * @return
     */
    @RequestMapping("checkPwd.do")
    public Result checkPwd(String oldPwd){
        try {
            Integer id = WebMvcUtil.getCurrentUser().getId();
            User user = userService.selectByPrimaryKey(id);
            if (user==null){
                return new Result(-1,"用户不存在");
            }
            if (!MD5Util.md5(oldPwd).equals(user.getPassword())){
                return new Result(-1,"旧密码不正确");
            }
            return new Result(200,null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1,"密码格式错误");
        }
    }

    @RequestMapping("queryCurrentUser.do")
    public Result queryCurrentUser(){
        User currentUser = userService.selectByPrimaryKey(WebMvcUtil.getCurrentUser().getId());
        System.out.println("currentUser = " + currentUser);
        return new Result(0,"查询成功",0L,currentUser);
    }
}
